#!/usr/bin/python

import os
import wx
import shutil
import sys
import cPickle

"""
 Module: cleanmove.py
  Original Release: 02/05/2013

  Ver: 1.0.2; Rev Last: 02/05/2013 - Previous: 02/04/2013
  - Clean new file names captured by Get Net Stream.
  - Copy or move new file names to designated target genre directories
    if cleaned file name does not exist in the target directory.

 Rev: 1.0.4; Rev Last: 02/22/2013 - Previous: 02/22/2013 (AEM)
   - Widen the clean and move window
   - Add total files in target dir to clean stats
   - Open target/src directory dialog to the last accessed location

 Copyright (C) 2012-2013  Arnold E. Morgan

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.

"""

class CleanStreamFilesDialog(wx.Dialog):
   """ The main dialog to enable cleaning and copying/moving
   new stream music files from the working directory to a
   designated destination target directory.
   """

   def __init__(self, parent, id, title):
      #wx.Dialog.__init__(self, parent, id, title, size=(695, 860))
      wx.Dialog.__init__(self, parent, id, title, size=(900, 860))

      self.FileFilterList = []   # List of file name filters and 
                                 # and replacement values
      self.FilterFileName = 'filterlist'
      self.LastMoveAction = False
      self.LastCopyAction = True
      self.LastTestAction = False
      self.LastSrcDir = ""
      self.LastTargetDir = ""
      self.MinFileSize = 0       # Clean only files >= this size

      self.ID_SOURCE_DIR = wx.NewId()
      self.ID_TARGET_DIR = wx.NewId()

      self.init_UI()
      self.SetTitle(title)

   def init_UI(self):
      MainDialogPanel = wx.Panel(self, -1)
      MainDialogPanel.SetBackgroundColour("#2CB7F3")

      MainSB = wx.StaticBox(MainDialogPanel, wx.ID_ANY,
                            label="  Clean Stream File Names  ",
                            pos=wx.Point(20, 10),
                            size=wx.Size(855, 840), style=0)

      # Retrieve last operating state of Src/Target file locations
      # and min file clean size.
      self.get_last_state()

      StreamCtrlsizer = wx.StaticBoxSizer(MainSB, wx.VERTICAL)

      SrcFileText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'New Source Files', (145, 30))
      SrcFileText.SetForegroundColour((255,255,255))
      SrcFileText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))

      self.NewSrcFileList = wx.ListBox(MainDialogPanel, wx.ID_ANY,
                           (40, 48), (350, 280), choices=[],
                           style=wx.LB_HSCROLL  | wx.LB_SINGLE | wx.LB_SORT)
      self.NewSrcFileList.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL))

      self.RefreshListButton = wx.Button(MainDialogPanel, wx.ID_ANY,
                             label='Refresh List',
                             pos=wx.Point(42, 340))

      TargetFileText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'New Target Files', (610, 30))
      TargetFileText.SetForegroundColour((255,255,255))
      TargetFileText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
      """
      self.NewTargetFileList = wx.ListBox(MainDialogPanel, wx.ID_ANY,
                           (400, 48), (250, 280), choices=[],
                           style=wx.LB_HSCROLL | wx.LB_SINGLE | wx.LB_SORT)
      """
      self.NewTargetFileList = wx.ListBox(MainDialogPanel, wx.ID_ANY,
                           (505, 48), (350, 280), choices=[],
                           style=wx.LB_HSCROLL | wx.LB_SINGLE | wx.LB_SORT)
      self.NewTargetFileList.SetFont(wx.Font(8,
                                             wx.SWISS, wx.NORMAL, wx.NORMAL))

      SizeFileText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'Copy files >=', (505, 345))
      SizeFileText.SetForegroundColour((255,255,255))
      SizeFileText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
      self.SizeFileBox = wx.TextCtrl(MainDialogPanel, wx.ID_ANY,
                                   value="", pos=(615, 340), size=(70, 24))
      SizeBytesText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'bytes', (695, 345))
      SizeBytesText.SetForegroundColour((255,255,255))
      SizeBytesText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
      self.SizeFileBox.SetValue(str(self.MinFileSize))


      #RadioSelectSizer = wx.StaticBoxSizer(MainSB, wx.HORIZONTAL)
      RadioSelectSizer = wx.StaticBoxSizer(MainSB, wx.VERTICAL)
      self.MoveRadio = wx.RadioButton( MainDialogPanel, -1, " Move ",
                                      (400, 60), style = wx.RB_GROUP )
      self.CopyRadio = wx.RadioButton( MainDialogPanel, -1, " Copy ",
                                      (400, 100) )
      self.TestRadio = wx.RadioButton( MainDialogPanel, -1, " Test Only ",
                                      (400, 140) )
      RadioSelectSizer.Add(self.MoveRadio)
      RadioSelectSizer.Add(self.CopyRadio)
      RadioSelectSizer.Add(self.TestRadio)
      self.MoveRadio.SetValue(self.LastMoveAction)
      self.CopyRadio.SetValue(self.LastCopyAction)
      self.TestRadio.SetValue(self.LastTestAction)

      self.DeleteSrcFileButton = wx.Button(MainDialogPanel, wx.ID_ANY,
                             label='<- Delete',
                             pos=wx.Point(405, 205))
      self.CleanButton = wx.Button(MainDialogPanel, wx.ID_ANY,
                             label='Clean ->',
                             pos=wx.Point(405, 270))

      self.SrcDirBox = wx.TextCtrl(MainDialogPanel, wx.ID_ANY,
                   value = self.LastSrcDir, pos = (40, 400), size = (350, 24))
      self.SrcDirButton = wx.Button(MainDialogPanel, self.ID_SOURCE_DIR,
                                   label='Source Directory',
                                   pos=wx.Point(42, 435))


      self.TargetDirBox = wx.TextCtrl(MainDialogPanel, wx.ID_ANY,
               value = self.LastTargetDir, pos = (505, 400), size = (350, 24))
      self.TargetDirButton = wx.Button(MainDialogPanel, self.ID_TARGET_DIR,
                                   label='Target Directory',
                                   pos=wx.Point(507, 435))

      NewFilterText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'New Filter', (42, 490))
      NewFilterText.SetForegroundColour((255,255,255))
      NewFilterText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))

      self.NewFilterBox = wx.TextCtrl(MainDialogPanel, wx.ID_ANY,
                                   value="", pos=(40, 510), size=(200, 24))

      NewReplaceText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'Replace Value', (262, 490))
      NewReplaceText.SetForegroundColour((255,255,255))
      NewReplaceText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
      self.NewReplaceBox = wx.TextCtrl(MainDialogPanel, wx.ID_ANY,
                                   value="", pos=(260, 510), size=(200, 24))

      self.SaveFilterButton = wx.Button(MainDialogPanel, wx.ID_ANY,
                    label='Save Filter', pos=wx.Point(480, 510))

      FilterListText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'Filters', (42, 560))
      FilterListText.SetForegroundColour((255,255,255))
      FilterListText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
      self.FilterList = wx.ListBox(MainDialogPanel, wx.ID_ANY,
                                        (40, 580), (250, 260), choices=[],
                                         style=wx.LB_HSCROLL | wx.LB_SINGLE)
      self.FilterList.SetFont(wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL))

      self.DeleteFilterButton = wx.Button(MainDialogPanel, wx.ID_ANY,
                    label='<- Delete', pos=wx.Point(305, 620))

      StatsListText = wx.StaticText(MainDialogPanel, wx.ID_ANY,
                                  'Clean Statistics', (507, 560))
      StatsListText.SetForegroundColour((255,255,255))
      StatsListText.SetFont(wx.Font(10, wx.SWISS, wx.NORMAL, wx.BOLD))
      self.StatsList = wx.ListBox(MainDialogPanel, wx.ID_ANY,
                                        (505, 580), (250, 220), choices=[],
                                         style=wx.LB_HSCROLL)

      DoneButton = wx.Button(MainDialogPanel, wx.ID_OK, label='Done',
                             pos=wx.Point(770, 810))

      # *** Sizer assignments ***
      StreamCtrlsizer.Add(SrcFileText)
      StreamCtrlsizer.Add(self.NewSrcFileList)
      StreamCtrlsizer.Add(self.RefreshListButton)

      StreamCtrlsizer.Add(RadioSelectSizer)
      StreamCtrlsizer.Add(self.DeleteSrcFileButton)
      StreamCtrlsizer.Add(self.CleanButton)

      StreamCtrlsizer.Add(TargetFileText)
      StreamCtrlsizer.Add(self.NewTargetFileList)

      StreamCtrlsizer.Add(SizeFileText)
      StreamCtrlsizer.Add(self.SizeFileBox)
      StreamCtrlsizer.Add(SizeBytesText)


      StreamCtrlsizer.Add(self.SrcDirBox)
      StreamCtrlsizer.Add(self.SrcDirButton )

      StreamCtrlsizer.Add(self.TargetDirBox)
      StreamCtrlsizer.Add(self.TargetDirButton )

      #StreamCtrlsizer.Add(StreamSrcText)
      #StreamCtrlsizer.Add(self.SrcDirSelect)

      #StreamCtrlsizer.Add(StationText)
      #StreamCtrlsizer.Add(self.SrcStationSelect)
      #StreamCtrlsizer.Add(TargetDirText)

      StreamCtrlsizer.Add(NewFilterText)
      StreamCtrlsizer.Add(self.NewFilterBox)

      StreamCtrlsizer.Add(NewReplaceText)
      StreamCtrlsizer.Add(self.NewReplaceBox)
      StreamCtrlsizer.Add(self.SaveFilterButton)

      StreamCtrlsizer.Add(FilterListText)
      StreamCtrlsizer.Add(self.FilterList)

      StreamCtrlsizer.Add(self.DeleteFilterButton)

      StreamCtrlsizer.Add(StatsListText)
      StreamCtrlsizer.Add(self.StatsList)

      StreamCtrlsizer.Add(DoneButton)

      # *** Button bindings ***
      self.SrcDirButton.Bind(wx.EVT_BUTTON, self.on_new_dir)
      self.TargetDirButton.Bind(wx.EVT_BUTTON, self.on_new_dir)
      self.SaveFilterButton.Bind(wx.EVT_BUTTON, self.save_new_filter)
      self.CleanButton.Bind(wx.EVT_BUTTON, self.on_clean_files)
      self.DeleteFilterButton.Bind(wx.EVT_BUTTON, self.on_delete_filter)
      self.DeleteSrcFileButton.Bind(wx.EVT_BUTTON, self.on_delete_src_file)
      self.RefreshListButton.Bind(wx.EVT_BUTTON, self.refresh_src_file_list)

      # Closing with the DoneButton is a special case.
      self.Bind(wx.EVT_BUTTON, self.on_close_window, id = wx.ID_OK)
      # This next event only happens for alt-F4 or sys window close
      # which I choose at this time to ignore.
      #self.Bind(wx.EVT_CLOSE, self.on_close_window)
   # ********* End of init_UI *********

   def on_close_window(self, event):
      """ The final actions when closing this frame. """

      self.save_last_state()
      event.Skip()     # Can now allow this event to close the window

   def save_last_state(self):
      """ Save the values of "important" controls to a serialized file
      at application shutdown time.

      Values will be recalled and reset at application start up.
      """

      StateValues = {}
      StateValues['SrcDir'] = self.SrcDirBox.GetValue()
      StateValues['TargetDir'] = self.TargetDirBox.GetValue()
      StateValues['MinFile'] = self.SizeFileBox.GetValue()
      StateValues['MoveAction'] = self.MoveRadio.GetValue()
      StateValues['CopyAction'] = self.CopyRadio.GetValue()
      StateValues['TestAction'] = self.TestRadio.GetValue()
      
      StateFile = open('cleanstate', 'w')
      cPickle.dump(StateValues, StateFile)
      StateFile.close()

   def get_last_state(self):
      """ What ever goes down must come up.

      Recall and make available operating state values
      from last shutdown.
      """

      LastState = {}
      StateMssg = ""
      ReadErr = False
      try:
         NewState = open('cleanstate', 'r')
         LastState = cPickle.load(NewState)
         NewState.close()
      except IOError, (errno, strerror):
         ReadErr = True
         StateMssg = "State file open error(%s): %s" % (errno, strerror)
      except:
         ReadErr = True
         StateMssg = "Unexpected state file open error: ", sys.exc_info()[0]
      finally:
         pass

      if not ReadErr:
         if LastState.has_key('SrcDir'):
            self.LastSrcDir = LastState['SrcDir']

         if LastState.has_key('TargetDir'):
            self.LastTargetDir = LastState['TargetDir']

         if LastState.has_key('MinFile'):
            self.MinFileSize = LastState['MinFile']

         if LastState.has_key('MoveAction'):
            self.LastMoveAction = LastState['MoveAction']

         if LastState.has_key('CopyAction'):
            self.LastCopyAction = LastState['CopyAction']

         if LastState.has_key('TestAction'):
            self.LastTestAction = LastState['TestAction']

   def on_new_dir(self, event):
      """  Show the DirDialog. Set selected text ctrl with 
      the chosen directory path value.

      if the request was for the src directory
      also populate the src file list.

      Example using custom ID values from
      http://zetcode.com/wxpython/events/
      """

      eid = event.GetId()
      #EventBox = "SrcDirBox"
      msg = ""        
      if eid == self.ID_SOURCE_DIR:
         msg = 'Source button clicked...'
         EventBox = self.SrcDirBox
      elif eid == self.ID_TARGET_DIR:
         msg = 'Target button clicked...'
         EventBox = self.TargetDirBox
      else:
         msg = 'Unknown button clicked, so we assume Source'
         EventBox = self.SrcDirBox

      DefDir = EventBox.GetValue()
      RtnDir = ""
      DlgAns = wx.DirDialog(self, "Choose a directory:",
                            DefDir,
                            style=wx.DD_DEFAULT_STYLE
                            #| wx.DD_DIR_MUST_EXIST
                            #| wx.DD_CHANGE_DIR
                            )
      if DlgAns.ShowModal() == wx.ID_OK:
         #Mssg = msg + "\n\nYou chose %s" % DlgAns.GetPath()
         #wx.MessageBox(Mssg, 'Info', wx.OK | wx.ICON_INFORMATION)
         RtnDir = DlgAns.GetPath()
         EventBox.SetValue(RtnDir)
         if eid == self.ID_SOURCE_DIR:
            self.populate_src_files(RtnDir)

      DlgAns.Destroy()

   def refresh_src_file_list(self, event):
      """ Reread the source directory and repopulate
      the NewSrcFileList ListBox.
      """

      if len(self.SrcDirBox.GetValue()) > 0:
         self.populate_src_files(self.SrcDirBox.GetValue())

   def get_filters(self):
      """ Bring in flle name filter values.
   
      Populate the FilterList list box with values
      from the serialized file.
      If any errors on open or read, eat them silently,
      but disable the "Clean" button.
      New filters can be defined with this dialog as well.
      """

      InFilters = []
      StateMssg = ""
      ReadErr = False
      try:
         NewFile = open(self.FilterFileName, 'r')
         InFilters = cPickle.load(NewFile)
         NewFile.close()
      except IOError, (errno, strerror):
         ReadErr = True
         StateMssg = "State file open error(%s): %s" % (errno, strerror)
      except:
         ReadErr = True
         StateMssg = "Unexpected state file open error: ", sys.exc_info()[0]
      finally:
         pass

      if not ReadErr:
         self.FileFilterList = InFilters
         self.populate_filter_vals(InFilters)
         self.CleanButton.Enable(True)
      else:
         self.CleanButton.Enable(False)
         #self.TargetDirButton.Enable(False)
         #self.SrcDirButton.Enable(False)

      return ReadErr

   def populate_filter_vals(self, InFilterVals):
      """ Populate the filter ListBox """

      for MyFilter in InFilterVals:
         self.FilterList.Append('"' + MyFilter[0] + '"' + " => " + \
                                '"' + MyFilter[1] + '"')

   def populate_src_files(self, SrcDir):
      """ Populate the NewSrcFileList ListBox with values from the
      source directory.
      """

      RawSrcFileList = os.listdir(SrcDir)

      self.NewSrcFileList.Clear()

      for SrcFileName in RawSrcFileList:
         if os.path.isfile(SrcDir + "/" + SrcFileName):
            self.NewSrcFileList.Append(SrcFileName)

   def save_new_filter(self, event):
      """ Add a new filter/replacement value pair to the serialied file
      and the FilterList ListBox.

      Filters exist as a list of 2-value tuples.
      """

      TempFilterVal = []
      NewFilterVal = self.NewFilterBox.GetValue()
      NewReplaceVal = self.NewReplaceBox.GetValue()
      if len(NewFilterVal) == 0:
         Mssg = "Enter a filter value in the New Filter box and " \
                "a value in the Replace Value box. Leaving the " \
                "Replace Value empty will replace with an " \
                "empty string."
         wx.MessageBox(Mssg, 'Info', wx.OK | wx.ICON_INFORMATION)
      else:
         NewFilter = (NewFilterVal, NewReplaceVal)

         self.sort_filter_list(NewFilter)
         self.save_serialized_filters()

         self.FilterList.Clear()
         self.populate_filter_vals(self.FileFilterList)
         self.CleanButton.Enable(True)

   def sort_filter_list(self, NewFilterVal):
      """ Sort the file filters.

      Order values by the largest string len filter value.
      Return the newly sorted list.
      """

      TempFilterList = self.FileFilterList
      TempFilterList.append(NewFilterVal)
      SortedNameList = []
      Indexer = 0
      MaxIndexList = [0,0]   # [index, size]

      while len(TempFilterList) > 0:
         Indexer = 0
         for (x,y) in TempFilterList:
            if len(x) > MaxIndexList[1]:
               MaxIndexList = [Indexer, len(x)]
            Indexer += 1

         SortedNameList.append(TempFilterList[MaxIndexList[0]])
         del TempFilterList[MaxIndexList[0]]
         MaxIndexList = [0,0]

      self.FileFilterList = SortedNameList

   def save_serialized_filters(self):
      """ Save the sorted filter values to a serialized file """

      MyFile = open(self.FilterFileName, 'w')
      cPickle.dump(self.FileFilterList, MyFile)
      MyFile.close()

   def on_delete_filter(self, event):
      """ Delete a filter value if selected.

      Remove item from self.FileFilterList, self.FilterList ListBox and
      the filter list serialized file.
      """

      SelectedIndex = self.FilterList.GetSelection()
      if (SelectedIndex != -1):
         self.FilterList.Delete(SelectedIndex)
         del self.FileFilterList[SelectedIndex]
         self.save_serialized_filters()
         if self.FilterList.GetCount() == 0:
            self.CleanButton.Enable(False)
      else:
         Mssg = "Select a filter value to be " \
                "deleted then click the \"Delete\" button."
         wx.MessageBox(Mssg, 'Info', wx.OK | wx.ICON_INFORMATION)

   def on_clean_files(self, event):
      """ Finally, the real reason this module exists.
      Execute the file name clean actions.
      """

      ExistsCnt = 0
      NewCnt = 0
      TooSmallCnt = 0
      OkToClean = False
      Mssg = ""
      DelMssgList = []
      CleanFileSize = self.parse_file_size(self.SizeFileBox.GetValue())

      # If min file size can't be converted to an integer,
      # set the MinFileSize bg TextCtrl red.
      if CleanFileSize == 0:
         self.SizeFileBox.SetBackgroundColour((255,0,0))
      else:
         self.SizeFileBox.SetBackgroundColour((255,255,255))

      CleanAction = self.get_clean_action()
      TargetDir = self.TargetDirBox.GetValue()
      SrcDir = self.SrcDirBox.GetValue()
      NewSrcFileListCnt = self.NewSrcFileList.GetCount()

      if  len(TargetDir) > 0 and len(SrcDir) > 0:
         OkToClean = True

      if NewSrcFileListCnt == 0:
         Mssg = "Select a source directory with file names needing to be " \
                "cleaned then click the \"Clean\" button."
      elif OkToClean == False:
         Mssg = "Select both %s target and source directories before clicking " \
                "the \"Clean\" button." % CleanAction
      else:
         TargetPath = self.set_full_file_path(TargetDir)
         SourcePath = self.set_full_file_path(SrcDir)
         self.NewTargetFileList.Clear()
         for index in range(NewSrcFileListCnt):
            RealFileName = self.NewSrcFileList.GetString(index)
            if os.path.getsize(SourcePath + RealFileName) >= CleanFileSize:
               CleanFileName = RealFileName
               for FilterKey in self.FileFilterList:
                  if FilterKey[0] in CleanFileName:
                     CleanFileName = CleanFileName.replace(FilterKey[0],
                                                           FilterKey[1])

               if os.path.exists(TargetPath + CleanFileName):
                  ExistsCnt += 1
                  TempListFileName = CleanFileName + " (EXISTS)"
               else:
                  NewCnt += 1
                  TempListFileName = CleanFileName

                  # "Move" or "Copy" -- copy to target directory
                  if CleanAction != "Test":
                     shutil.copy2(SourcePath + RealFileName,
                                  TargetPath + CleanFileName)

                  # If "Move" -- delete from source directory also
                  if CleanAction == "Move":
                     (DelSuccess, DelMssg) = self.delete_src_file(SourcePath + \
                                                                  RealFileName)
                     if not DelSuccess:
                        DelMssgList.append(DelMssg)

               self.NewTargetFileList.Append(TempListFileName)
               # *** End of MinFileSize check ***
            else:
               TooSmallCnt += 1

         NewTargetFileCnt = self.GetDirFileCnt(TargetDir)

         self.StatsList.Clear()
         self.StatsList.Append("New Files: " + str(NewCnt))
         self.StatsList.Append("Existing Files: " + str(ExistsCnt))
         self.StatsList.Append("Total Files: " + str(NewSrcFileListCnt))
         self.StatsList.Append("Not Min Size Files: " + str(TooSmallCnt))
         self.StatsList.Append("%s Min File Size: %s" % (CleanAction,
                                                         str(CleanFileSize)))
         self.StatsList.AppendItems(DelMssgList)
         self.StatsList.Append("Total Target Files: " + str(NewTargetFileCnt))    

      if len(Mssg) > 0:
         wx.MessageBox(Mssg, 'Info', wx.OK | wx.ICON_INFORMATION)

   def get_clean_action(self):
      """ Get and return clean action radio button selection.

      Return the selected action as a string.
      """
      RtnAction = ""
      if self.MoveRadio.GetValue() == True:
         RtnAction = "Move"
      elif self.CopyRadio.GetValue() == True:
         RtnAction = "Copy"
      else:
         RtnAction = "Test"

      return RtnAction

   def set_full_file_path(self, FullFilePath):
      """ Correct path trailing slash if needed. """

      TempFilePath = FullFilePath
      if FullFilePath[-1:] != '/' and FullFilePath[-1:] != '\\':
         TempFilePath = FullFilePath + '/'

      return TempFilePath

   def parse_file_size(self, RawFileSize):
      """ Make sure file size in input box is a usable number.

      I don't know why someone would enter a decimal,
      but attempt to convert to an integer.
      Return either the integer of the input argument
      or 0 (zero) if it can't be converted.
      """

      # Ok, make an allowance for commas, but that's it.
      MyStrNum = RawFileSize.replace(",", "")
      MyIntFloat = 0
      try:
         MyIntFloat = int(float(MyStrNum))
      except ValueError:
         #print "MyIntFloat conversion not successful"
         MyIntFloat = 0

      return MyIntFloat

   def on_delete_src_file(self, event):
      """ Delete a selected file from the NewSrcFileList ListBox
      and source directory.
      """

      SrcPath = self.set_full_file_path(self.SrcDirBox.GetValue())
      SelectedIndex = self.NewSrcFileList.GetSelection()
      if (SelectedIndex != -1):
         SelectedFileName = self.NewSrcFileList.GetString(SelectedIndex)
         #Mssg = "\nDeleting index %d: %s" % (SelectedIndex, SrcPath + \
         #                                    SelectedFileName)
         #wx.MessageBox(Mssg, 'Info', wx.OK | wx.ICON_INFORMATION)
         
         (DelSuccess, DelMssg) = self.delete_src_file(SrcPath + \
                                                      SelectedFileName)
         if DelSuccess:
            self.NewSrcFileList.Delete(SelectedIndex)
         else:
            wx.MessageBox(DelMssg, 'Info', wx.OK | wx.ICON_INFORMATION)
      else:
         Mssg = "Select a source file to be " \
                "deleted then click the \"Delete\" button."
         wx.MessageBox(Mssg, 'Info', wx.OK | wx.ICON_INFORMATION)

   def delete_src_file(self, FullSrcPath):
      """ Remove a source file from disk.

      Full path is provided.
      If delete was successful, return True. Otherwise return False
      and the message text of why.
      """

      DelOK = True
      StateMssg = ""
      try:
         os.remove(FullSrcPath)
      except IOError, (errno, strerror):
         DelOK = False
         StateMssg = "Source file %s delete error(%s): %s" % \
              (FullSrcPath, errno, strerror)
      except:
         DelOK = False
         StateMssg = "Unexpected source file %s delete error: %s " % \
              (FullSrcPath, str(sys.exc_info()))
         #     (FullSrcPath, sys.exc_info()[0])
      finally:
         pass

      return (DelOK, StateMssg)

   def GetDirFileCnt(self, RequestDir):
      """ Return number of files in the requested directory. """

      FileCnt = len([FileList for FileList in os.listdir(RequestDir) \
                    if os.path.isfile(os.path.join(RequestDir, FileList))])
      return FileCnt
